package cn.simple.manager.web;

import cn.simple.manager.exception.DataSourceKeyNotFountException;
import cn.simple.manager.todo.ResponseEntity;
import org.springframework.core.MethodParameter;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

@RestControllerAdvice
public class CurdExceptionHandler implements ResponseBodyAdvice<Object> {
    @ExceptionHandler(DataSourceKeyNotFountException.class)
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    public ResponseEntity dataSourceKeyNotFount(DataSourceKeyNotFountException e){

        return ResponseEntity.ERRO(e.getMessage());
    }

    @Override
    public boolean supports(MethodParameter methodParameter, Class<? extends HttpMessageConverter<?>> aClass) {
        System.out.println(methodParameter);
        return true;
    }

    @Override
    public Object beforeBodyWrite(Object o, MethodParameter methodParameter, MediaType mediaType, Class<? extends HttpMessageConverter<?>> aClass, ServerHttpRequest serverHttpRequest, ServerHttpResponse serverHttpResponse) {
       if(o instanceof ResponseEntity || methodParameter.getMethod().getName().equals("error")){
            return o;
       }
        return ResponseEntity.ok(o);
    }
}
